package my.android.util.r2;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import code.bigmama.http.multipart.ByteArrayPartSource;
import code.bigmama.http.multipart.FilePart;
import code.bigmama.http.multipart.MultipartEntity;
import code.bigmama.http.multipart.Part;
import android.util.Log;

public final class AndroidNetwork extends java.lang.Object
{
	public static final String	DEBUG_TAG	= "AndroidNetwork";

	private HTTP				http;

	public AndroidNetwork(String url)
	{
		super();
		http = new HTTP(url);
		http.connect();
	}
	
	public static void upload2(String address)
	{
		URL url = null;
		URLConnection conn = null;

			try
			{
				url = new URL(address);
				conn = url.openConnection();
				
				OutputStream os = conn.getOutputStream();
				
			}
			catch (MalformedURLException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			
			
	}

	public static void post(String address)
	{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(address);

		post.setHeader("User-Agent", "Mozilla/4.0");
		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
		post.setHeader("ACCEPT", "text/plain");

		String body = null;

		try
		{
			String username = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("bebeto", "UTF-8");
			String password1 = URLEncoder.encode("password1", "UTF-8") + "=" + URLEncoder.encode("30434", "UTF-8");
			String password2 = URLEncoder.encode("password2", "UTF-8") + "=" + URLEncoder.encode("30434", "UTF-8");
			String email = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode("manyfun@naver.com", "UTF-8");

			body = username + "&" + password1 + "&" + password2 + "&" + email;

			HttpEntity entity = new ByteArrayEntity(body.getBytes());
			post.setEntity(entity);

		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
			Log.e(DEBUG_TAG, e.getMessage());
		}

		try
		{
			HttpResponse response = client.execute(post);

			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() == HttpStatus.SC_OK)
			{
				Log.d(DEBUG_TAG, "Post completed");
			}
			else
			{
				Log.d(DEBUG_TAG, "Post failed: " + status.getReasonPhrase());
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
		}
	}

	public static void upload(String address, String path, String name)
	{
		HttpClient client = new DefaultHttpClient();
		
		File file = new File(path, name);
		
		HttpPost post = new HttpPost(address);
		
		try
		{
//			ByteBuffer by = ByteBuffer.allocate( (int)file.length() );
			
//			FileInputStream fis = new FileInputStream( file );
			
//			fis.getChannel().read( by );
			
//			ByteArrayEntity entity = new ByteArrayEntity(by.array());
			
			Part[] parts = {new FilePart(name, file), new FilePart(name, file)};
			
			MultipartEntity entity = new MultipartEntity( parts, post.getParams() );
			
			post.setEntity( entity);
			
			HttpResponse response = client.execute(post);

			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() == HttpStatus.SC_OK)
			{
				Log.d(DEBUG_TAG, "Post completed");
			}
			else
			{
				Log.d(DEBUG_TAG, "Post failed: " + status.getReasonPhrase());
			}
			
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
/*	  
		String absolute = path + File.separator + name;

		HttpClient client = new DefaultHttpClient();

		HttpPost post = new HttpPost(address);

		MultipartEntity entity = new MultipartEntity(null);
		
		File file = new File(absolute);
		
		entity.addPart(name, new FileEntity(file, absolute));
		
//		post.setHeader(entity.getContentEncoding());
//		post.setHeader("ACCEPT", "image/jpeg");
//		post.setHeader(entity.getContentType());
		
		post.setEntity(entity);

		try
		{
			HttpResponse response = client.execute(post);

			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() == HttpStatus.SC_OK)
			{
				Log.d(DEBUG_TAG, "Post completed");
			}
			else
			{
				Log.d(DEBUG_TAG, "Post failed: " + status.getReasonPhrase());
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
*/
	}

	public InputStream getStream()
	{
		return null;
	}

	public InputStream getHttpContentStream()
	{
		InputStream is = null;

		if (this.http != null)
		{
			is = http.getData();
		}

		return is;
	}

	public int getSizeOfHTTPContent()
	{
		int size = 0;

		if (this.http != null)
		{
			size = http.getSize();
		}

		return size;
	}

	public void disconnectHTTP()
	{
		if (http != null)
		{
			this.http.disconnect();
		}
	}

	public static String getLocalIpAddress()
	{
		try
		{

			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
			{
				NetworkInterface ni = en.nextElement();

				for (Enumeration<InetAddress> enumIpAddr = ni.getInetAddresses(); enumIpAddr.hasMoreElements();)
				{
					InetAddress inetAddress = enumIpAddr.nextElement();

					if (!inetAddress.isLoopbackAddress())
					{
						return inetAddress.getHostAddress();
					}
				}
			}
		}
		catch (SocketException ex)
		{
			Log.e(DEBUG_TAG, ex.toString());
		}

		return null;
	}
}

class HTTP extends java.lang.Object
{
	public static final String	DEBUG_TAG	= "HTTP";

	private InputStream			is;

	private int					size;

	private HttpURLConnection	httpConn;

	private String				url;

	public HTTP(String url)
	{
		super();

		this.size = 0;
		this.is = null;
		this.httpConn = null;
		this.url = url;
	}

	public int post2()
	{
		String rawData = "username=bebeto&password1=30434&email=manyfun@naver.com";

		String encodedData = null;
		URL url = null;

		try
		{
			encodedData = URLEncoder.encode(rawData, "UTF-8");

			url = new URL(this.url);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(encodedData);
			wr.flush();

		}
		catch (MalformedURLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return 1;
	}

	public int post()
	{
		HttpURLConnection http_conn = null;
		URL url = null;
		URLConnection conn = null;
		String body = null;

		try
		{
			String username = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("bebeto", "UTF-8");
			String password1 = URLEncoder.encode("password1", "UTF-8") + "=" + URLEncoder.encode("30434", "UTF-8");
			String password2 = URLEncoder.encode("password2", "UTF-8") + "=" + URLEncoder.encode("30434", "UTF-8");
			String email = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode("manyfun@naver.com", "UTF-8");

			body = username + "&" + password1 + "&" + password2 + "&" + email;
		}
		catch (UnsupportedEncodingException e2)
		{
			e2.printStackTrace();
		}

		String agent = "Mozilla/4.0";
		String ContentType = "application/x-www-form-urlencoded";
		String accept = "text/plain";

		OutputStreamWriter wr = null;

		try
		{
			url = new URL(this.url);
			conn = url.openConnection();
			http_conn = (HttpURLConnection) conn;

			http_conn.setAllowUserInteraction(true);
			http_conn.setDoOutput(true);
			http_conn.setRequestMethod("POST");
			http_conn.setRequestProperty("User-Agent", agent);
			http_conn.setRequestProperty("Content-Type", ContentType);
			// http_conn.setRequestProperty("Content-Length",
			// String.valueOf(body.length()));
			http_conn.setRequestProperty("ACCEPT", accept);

			wr = new OutputStreamWriter(http_conn.getOutputStream());

			wr.write(body);

			// System.out.println(String.format("HTTP response code : %d  message: %s",
			// http_conn.getResponseCode(), http_conn.getResponseMessage()));

		}
		catch (IOException e)
		{
			e.printStackTrace();
			// Log.e(DEBUG_TAG, e.getMessage());
		}
		finally
		{
			try
			{
				wr.flush();
				wr.close();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}

		}

		return 1;
	}

	public void post3()
	{
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://bigmama.goanygate.com:8080/accounts/register_user/");

		post.setHeader("User-Agent", "Mozilla/4.0");
		post.setHeader("Content-Type", "application/x-www-form-urlencoded");
		post.setHeader("ACCEPT", "text/plain");

		String body = null;

		try
		{
			String username = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("bebeto", "UTF-8");
			String password1 = URLEncoder.encode("password1", "UTF-8") + "=" + URLEncoder.encode("30434", "UTF-8");
			String password2 = URLEncoder.encode("password2", "UTF-8") + "=" + URLEncoder.encode("30434", "UTF-8");
			String email = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode("manyfun@naver.com", "UTF-8");

			body = username + "&" + password1 + "&" + password2 + "&" + email;

			HttpEntity entity = new ByteArrayEntity(body.getBytes());
			post.setEntity(entity);

		}
		catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
			Log.e(DEBUG_TAG, e.getMessage());
		}

		try
		{
			HttpResponse response = client.execute(post);

			StatusLine status = response.getStatusLine();

			if (status.getStatusCode() == HttpStatus.SC_OK)
			{
				Log.d(DEBUG_TAG, "Method completed");
			}
			else
			{
				Log.d(DEBUG_TAG, "Method failed: " + status.getReasonPhrase());
			}
		}
		catch (ClientProtocolException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public boolean connect()
	{
		URL url = null;
		URLConnection conn = null;

		try
		{
			String new_url = this.url.replace("#", "%23");

			Log.d(DEBUG_TAG, new_url);

			url = new URL(new_url);

			conn = url.openConnection();

			this.httpConn = (HttpURLConnection) conn;

			// this.httpConn.setAllowUserInteraction(false);
			// this.httpConn.setInstanceFollowRedirects(true);
			// this.httpConn.setRequestMethod("GET");
			// this.httpConn.connect();

			// if((this.httpConn.getResponseCode() ==
			// HttpURLConnection.HTTP_OK))
			// {
			// this.httpConn.setDoInput( true );
			// this.httpConn.connect();
			// }

		}
		catch (MalformedURLException e)
		{
			e.printStackTrace();
			Log.e(DEBUG_TAG, e.getMessage());
			return false;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			Log.e(DEBUG_TAG, e.getMessage());
			return false;
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			Log.e(DEBUG_TAG, ex.getMessage());
			return false;
		}

		return true;

	}

	public InputStream getData()
	{
		if (this.httpConn == null)
		{
			throw new NullPointerException();
		}

		int response = -1;

		try
		{
			response = this.httpConn.getResponseCode();

			if (response == HttpURLConnection.HTTP_OK)
			{
				this.size = this.httpConn.getContentLength();
				this.is = this.httpConn.getInputStream();
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
			Log.e(DEBUG_TAG, e.getMessage());

			return null;
		}

		return is;
	}

	public void disconnect()
	{
		// try
		// {
		// if( this.is != null )
		// this.is.close();

		if (this.httpConn != null)
		{
			this.httpConn.disconnect();
		}

		Log.d(DEBUG_TAG, "success to disconnect hppt connection");

		// }
		// catch ( IOException e )
		// {
		// Log.e(DEBUG_TAG, "failed to disconnect hppt connection");
		// }

	}

	public int getSize()
	{
		return this.size;
	}

}
